package com.aiapphub.BaseCode.controller;

import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.BaseCode.entity.Role;
import com.aiapphub.BaseCode.service.RoleService;
import com.aiapphub.BaseCode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/admin/acl/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 获取用户可分配的角色列表
     * @param userId 用户ID
     * @return 包含所有角色和已分配角色的响应结果
     */
    @GetMapping("/toAssign/{userId}")
    public ResponseResult toAssign(@PathVariable Long userId) {
        try {
            // 获取所有未删除的角色
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_deleted", 0);
            List<Role> allRoles = roleService.list(queryWrapper);
            
            // 获取用户已分配的角色
            List<Role> assignedRoles = userService.getAssignedRoles(userId);
            
            // 构造返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("allRoles", allRoles);
            result.put("assignedRoles", assignedRoles);
            
            return ResponseResult.okResult(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(500, "获取角色列表失败");
        }
    }

    /**
     * 给用户分配角色
     * @param userId 用户ID
     * @param roleId 角色ID字符串，多个角色ID用逗号分隔
     * @return 操作结果
     */
    @PostMapping("/doAssign")
    public ResponseResult doAssign(@RequestParam Long userId, @RequestParam String roleId) {
        try {
            // 保存用户和角色的关联关系
            boolean result = userService.assignRolesToUser(userId, roleId);
            return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "角色分配失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(500, "角色分配失败：" + e.getMessage());
        }
    }
    
    /**
     * 移除用户的指定角色
     * @param userId 用户ID
     * @param roleId 角色ID
     * @return 操作结果
     */
    @DeleteMapping("/removeRole/{userId}/{roleId}")
    public ResponseResult removeRole(@PathVariable Long userId, @PathVariable Long roleId) {
        try {
            // 移除用户的指定角色
            boolean result = userService.removeRole(userId, roleId);
            return result ? ResponseResult.okResult() : ResponseResult.errorResult(500, "角色移除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(500, "角色移除失败：" + e.getMessage());
        }
    }
}